import { AfterContentInit, AfterViewInit, Component, ContentChildren, ElementRef, EventEmitter, OnDestroy, OnInit, Output, QueryList, TemplateRef, ViewChild, ViewChildren } from '@angular/core';
import { Istudent } from '../../istudent';
import { SharedDataService } from '../../../app/service/shared-data.service';
import { UserService } from 'src/app/service/user.service';
import IUser from 'src/app/pojo/IUser';
import * as qs from "qs"
import { Subject, Subscription } from 'rxjs';

@Component({
  selector: 'app-student-list',
  templateUrl: './student-list.component.html',
  styleUrls: ['./student-list.component.scss']
})
export class StudentListComponent implements OnInit,OnDestroy{


  // 模糊查询用名字
  filterName = "";
  selectedSexyValue: string = '2'; // 默认选项 男女
  sort: number = 0; // 0:不排序，1：升序，2：降
  selectStudent: Istudent | undefined = undefined;

  @Output()
  itemclick: EventEmitter<Istudent> = new EventEmitter<Istudent>();
  selectStudentClick(sstudent: Istudent) {
    this.selectStudent = sstudent;
    this.itemclick.emit(this.selectStudent);
  }


  // 构造函数
  constructor(private sharedData: SharedDataService, private userService: UserService) {

    for (let item of this.studentList) {
      // 求平均分
      item.pingjun = ((item.shuxue + item.yuwen + item.yinyu) / 3);
    }
  }
  ngOnDestroy(): void {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
    this.subscriptions.forEach(sub => sub.unsubscribe());
  }
  // 添加一个学生
  addStudent() {
    let t_Student: Istudent = {
      img: "/assets/images/2.png",
      name: "szq2",
      age: 10,
      intersting: ["篮球", "排球", "乒乓球"],
      shuxue: 60,
      yuwen: 73.233,
      yinyu: 60,
      pingjun: 0,
      zongchegnji: 0,
      beizhu: "",
      sexy: "1"
    };
    this.studentListBak.push(t_Student);
    this.updateView();

  }

  users: IUser[] = [];

  private ngUnsubscribe: Subject<void> = new Subject<void>();
  private subscriptions: Subscription[] = [];
  
  // 订阅刷新
  ngOnInit() {
    const subscription0 =    this.sharedData.updateNeeded$.subscribe((data) => {
      console.log('Received data:', data);
      // 在这里处理接收到的数据，比如更新组件视图
      this.filterName = data;
      this.updateView();
    });
    let payload = qs.stringify({
      name: "",
      start: 0,
      pageSize: 20,
    });

    const subscription1 =  this.userService.getUsers(payload).pipe(
    ).subscribe(
      {
        next: (users: IUser[]) => {
          this.users = users;
          console.log("-----------------network--------------");
          console.log(this.users);
        },
        error: (error) => {
          console.error('Error fetching users:', error);
        },
        complete: () => console.log('Complete')
      }
      
    );
    this.subscriptions.push(subscription0);
    this.subscriptions.push(subscription1);
   

    // this.userService.getUsers(payload).subscribe(
    //   (users: IUser[]) => {
    //     this.users = users;
    //     console.log("-----------------network--------------" );
    //     console.log(this.users );
    //   },
    //   (error) => {
    //     console.error('Error fetching users:', error);
    //   }
    // );

  }

  // 更新组件的数据
  updateView() {
    // 模糊查询
    this.studentList = this.studentListBak.filter(item => (item.name.includes(this.filterName)));
    // 男女查询
    this.studentList = this.studentList.filter(item => (this.selectedSexyValue == '2' || item.sexy == this.selectedSexyValue));
    // 排序
    this.sortItems(this.studentList);
  }


  private student: Istudent = {
    img: "/assets/images/2.png",
    name: "szq",
    age: 10,
    intersting: ["篮球", "排球", "乒乓球"],
    shuxue: 60,
    yuwen: 53.233,
    yinyu: 60,
    pingjun: 0,
    zongchegnji: 0,
    beizhu: "",
    sexy: "1"
  };
  private student2: Istudent = {
    img: "/assets/images/3.png",
    name: "hlx",
    age: 20,
    intersting: ["跳绳", "跑步", "骑车"],
    shuxue: 93,
    yuwen: 99.98,
    yinyu: 93,
    pingjun: 0,
    zongchegnji: 0,
    beizhu: "",
    sexy: "0"
  };
  private student3: Istudent = {
    img: "/assets/images/1.png",
    name: "syh",
    age: 20,
    intersting: ["跳绳", "跑步", "骑车"],
    shuxue: 140,
    yuwen: 120,
    yinyu: 135,
    pingjun: 0,
    zongchegnji: 0,
    beizhu: "",
    sexy: "0"
  };

  studentList: Istudent[] = [this.student, this.student2, this.student3];
  // studentList: Istudent[] = [this.student];

  studentListBak: Istudent[] = [...this.studentList]

  // 排序
  sortItemsClick(tstudent: Istudent[]) {
    // 0:不排序，1：升序，2：降序
    if (this.sort === 0) {
      this.sort = 1; //1：升序
      tstudent.sort((a, b) => a.pingjun - b.pingjun);
    } else if (this.sort === 1) {
      this.sort = 2; //2：降序
      tstudent.sort((a, b) => b.pingjun - a.pingjun);
    } else if (this.sort === 2) {
      this.sort = 1; //1：升序
      tstudent.sort((a, b) => a.pingjun - b.pingjun);
    }
  }
  // 排序
  sortItems(tstudent: Istudent[]) {
    // 0:不排序，1：升序，2：降序
    if (this.sort === 0) {
    } else if (this.sort === 1) {
      tstudent.sort((a, b) => a.pingjun - b.pingjun);
    } else if (this.sort === 2) {
      tstudent.sort((a, b) => b.pingjun - a.pingjun);
    }
  }

  //男女筛选
  onFilterSexy(value: string) {
    // 使用filter和箭头函数
    console.log(this.studentListBak);
    this.selectedSexyValue = value
    // this.selectedSexyValue=event.target.value;
    this.updateView();
  }
}
